<template>
  <div class="warpper">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="auto" label-position="right">
        <el-form-item label="Customer Name">
          <el-input v-model="searchForm.name" @keyup.enter.native="search" placeholder="Enter customername">
          </el-input>
        </el-form-item>

        <el-form-item label="Group" prop="group_id">
          <el-select v-model="searchForm.group_id" placeholder="Select Groups">
            <el-option v-for="item in group" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Salesman" prop="salesman">
          <el-select v-model="searchForm.salesman" placeholder="Select Salesman">
            <el-option v-for="item in salesman" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Countries">
          <el-input v-model="searchForm.countries" placeholder="Enter Countries" style="width: 108%;">
          </el-input>
        </el-form-item>
        <br />

        <el-form-item label="Customer ID">
          <el-input v-model="searchForm.customerid" @keyup.enter.native="search" placeholder="Enter customerid">
          </el-input>
        </el-form-item>

        <el-form-item label="Contract Period" prop="contract">
          <el-date-picker v-model="searchForm.contract" type="datetimerange" range-separator="-"
            start-placeholder="Select Start Date" end-placeholder="Select End Date" value-format="MM-dd-yyyy"
            style="width: 137.3%;">
          </el-date-picker>
        </el-form-item>
        <br />
        <el-form-item>
          <el-button @click="find()" plain style="margin-left: 24px;">Search</el-button>
          <el-button type="primary" v-permission="['customers.store']" plain @click="customeradd">+ New</el-button>
          <el-button type="primary" v-permission="['customers.view']" plain @click="exportData">Export</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table @sort-change="handleSortChange" :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="name" label="Name" width="160" align="center" sortable="name" />
        <el-table-column prop="customerid" label="Customer ID" width="160" align="center" sortable="customerid" />

        <el-table-column prop="groupname" label="Group" width="140" align="center" sortable="groupname">
          <template v-slot="scope">
            <span>{{ scope.row.groupname }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cenddate" label="Contract Period" width="200" align="center" sortable="cenddate">
          <template v-slot="scope">
            <span v-if="scope.row.cenddate && parseDateStr(scope.row.cenddate)<mydate"
              style="color:#fb8503">Expired</span>
            <span v-else>{{ scope.row.cstartdate }}~{{ scope.row.cenddate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="salesman" label="Salesman" width="110" sortable="salesman" />
        <el-table-column prop="creditlimit" label="Credit Limit(S$)" width="160" align="center" sortable="creditlimit">
          <template v-slot="scope">
            <span>{{ scope.row.creditlimit }}/{{ scope.row.creditermoriginal }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="crediterm" label="Periodic Payment" width="160" align="center" sortable="crediterm">
          <template v-slot="scope">
            <span>{{ scope.row.crediterm }}{{ scope.row.crediterm_data }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="skucount" label="Product" width="100" align="center" sortable="skucount">
          <template v-slot="scope">
            <span>{{scope.row.skucount}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deaddresscount" label="Address" width="100" align="center" sortable="deaddresscount">
          <template v-slot="scope">
            <span @click="gotoadd(scope.row.id)">{{scope.row.deaddresscount}}</span>
          </template>
        </el-table-column>

        <el-table-column prop="countries" label="Countries" width="110" align="center" sortable="countries">
          <template v-slot="scope">
            <span>{{scope.row.countries}}</span>
          </template>
        </el-table-column>


        <el-table-column prop="created_at" label="Created Time" min-width="120" sortable="created_at" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="200">
          <template slot-scope="scope">
            <el-button plain v-permission="['customers.show']" @click="edit(scope.row.id)">edit</el-button>
            <el-button plain type="danger" v-permission="['customers.destroy']"
              @click="del(scope.row.id)">delete</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    update,
    exportData as skuexport
  } from "@/api/customer";
  import {
    index as adminindex
  } from "@/api/admin";
  import {
    index
  } from "@/api/customer_group";
  export default {
    name: "customerIndex",
    mixins: [CURD],
    data() {
      return {
        mydate: '',
        formData: {},
        status: [{
          id: 1,
          name: "Normal",
        }, {
          id: 2,
          name: "Hidden",
        }],
        salesman: [],
        module: "customer",
        newTitle: "New customer",
        editTitle: "Edit customer",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        group: [],
        deptOptions: [],
        searchForm: {

        },

      };
    },
    async created() {
      const today = new Date();
      this.mydate = today
      try {
        const {
          data
        } = await index(1, 100); // 假设index是一个异步函数
        this.group = data;
        this.group.unshift({
          id: null,
          value: null,
          name: 'All'
        });
      } catch (error) {
        console.error('Failed to fetch group:', error);
      }

      try {
        const {
          data
        } = await adminindex(1, 100, {
          usertype: 1
        });
        this.salesman = data.map(item => ({
          id: item.nickname, // 将 nickname 的值赋给 id
          name: item.nickname // 将 nickname 的值赋给 name
        }));

        // 在数组最前面添加一个特定的对象
        this.salesman.unshift({
          id: null,
          name: 'ALL'
        });
      } catch (error) {
        console.error('Failed to fetch staff:', error);
      }
    },
    methods: {
      handleSortChange({ prop, order }) {
        this.searchForm.orderBy = prop;
        this.searchForm.orderType = order === 'ascending' ? 'asc' : 'desc';
        this.fetchData();
      },
      async fetchData() {
        let { index } = require(`@/api/${this.module}`);
        const res = await index(
          this.page.current_page,
          this.page.per_page,
          this.searchForm  // 包含了排序参数
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data;
        } else {
          this.tableData = res.data;
        }
        if (res.meta) {
          // 分页
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      async exportData() {
        const resv = await skuexport();
        this.exportFile('Customer_Master_Listing_' + Date.now() + '.xlsx', resv);
      },
      exportFile(fileName, res) {
        const content = res;
        const blob = new Blob([content], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = window.URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          window.URL.revokeObjectURL(elink.href); // 释放 URL对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          window.navigator.msSaveBlob(blob, fileName);
        }
      },
      parseDateStr(dateStr) {
        const [month, day, year] = dateStr.split('-').map(Number);
        return new Date(year, month - 1, day);
      },
      customeradd() {
        this.$router.push({
          path: '/customer/customeradd',
          query: {
            id: null
          }
        })
      },
      async edit(id) {
        this.$router.push({
          path: '/customer/editcustomer',
          query: {
            id: id
          }
        })
      },
      async gotoadd(id) {
        this.$router.push({
          path: '/customer/editcustomer',
          query: {
            id: id,
            type: "d"
          }
        })

      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      getStatusColor(row) { // 状态颜色
        if (row.status === 'Normal') {
          return 'green-text';
        } else if (row.status === 'Hidden') {
          return 'red-text';
        } else {
          return 'yellow-text';
        }
      },
      normalizer(node) {
        if (node.children && node.children.length === 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }
        return tree;
      },
      adjustOrder(row) {
        row.isEdit = true;
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            if (this.isUploadFile) {
              // 更改了图片，则必须先传图片
              this.$refs.uploadAvatar.submit();
            } else {
              this.save(form);
            }
          } else {
            this.$message.error("Data filling error, please fill in again according to the requirements");
          }
        });
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.suppliers = this.formData.suppliersdata.toString();
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);

                let {
                  info
                } = await store(this.formData);
                this.$message.success("Save successfully");
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.image = data.url;
              this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
        };
      },
      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }
    }

  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>
